#include "pcm_towav.h"
#include <QFileInfo>
#include <QDebug>
#include <QFile>


pcm_towav::pcm_towav(QString pathWav, QString pathPcm, int NumChannels, int SampleRate, int BitsPerSample) {
    QFile pcmFile(pathPcm);
    QFile wavFile(pathWav);

    if (!pcmFile.open(QIODevice::ReadOnly)) {
        qCritical() << "无法打开 PCM 文件：" << pathPcm;
        return;
    }

    if (!wavFile.open(QIODevice::WriteOnly)) {
        qCritical() << "无法打开 WAV 文件：" << pathWav;
        return;
    }

    // 文件头部
    WAVE_HEADER pcmHEADER;
    WAVE_FMT pcmFMT;
    WAVE_DATA pcmDATA;

    // PCM 数据大小（15秒）
    qint64 pcmSize = SampleRate * NumChannels * (BitsPerSample / 8) * 15;

    // 填充 WAV 头部信息
    memcpy(pcmHEADER.ChunkID, "RIFF", 4);
    memcpy(pcmHEADER.Format, "WAVE", 4);
    pcmHEADER.ChunkSize = 36 + pcmSize;

    memcpy(pcmFMT.Subchunk1ID, "fmt ", 4);
    pcmFMT.Subchunk1Size = 16;
    pcmFMT.AudioFormat = 1;
    pcmFMT.NumChannels = NumChannels;
    pcmFMT.SampleRate = SampleRate;
    pcmFMT.ByteRate = SampleRate * NumChannels * (BitsPerSample / 8);
    pcmFMT.BlockAlign = NumChannels * (BitsPerSample / 8);
    pcmFMT.BitsPerSample = BitsPerSample;

    memcpy(pcmDATA.Subchunk2ID, "data", 4);
    pcmDATA.Subchunk2Size = pcmSize;

    // 写入 WAV 文件头
    wavFile.write(reinterpret_cast<char*>(&pcmHEADER), sizeof(WAVE_HEADER));
    wavFile.write(reinterpret_cast<char*>(&pcmFMT), sizeof(WAVE_FMT));
    wavFile.write(reinterpret_cast<char*>(&pcmDATA), sizeof(WAVE_DATA));

    // 读取 PCM 数据并写入 WAV 文件
    QByteArray pcmData = pcmFile.read(pcmSize);
    wavFile.write(pcmData);

    // 将未处理的 PCM 数据保存到原文件
    QByteArray pcmData2 = pcmFile.readAll();
    pcmFile.close();

    QFile tempFile("temp.pcm");
    if (tempFile.open(QIODevice::WriteOnly)) {
        tempFile.write(pcmData2);
        tempFile.close();
        pcmFile.remove();
        tempFile.rename(pathPcm);
    }

    wavFile.close();
    qDebug() << "PCM 转 WAV 完成：" << pathWav;
}
